/**
 * <p>
 * 版权所有：中企动力
 * </p>
 * <p>
 * 未经本公司许可，不得以任何方式复制或使用本程序任何部分
 * </p>
 */
package com.ce.pms.occupation.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.ce.pms.base.web.PmsBaseAction;
import com.ce.pms.common.web.ICacheManage;
import com.ce.pms.exception.BusinessException;
import com.ce.pms.exception.UILayerException;
import com.ce.pms.house.service.IBuildingService;
import com.ce.pms.house.vo.BuildingVO;
import com.ce.pms.occupation.service.IDispatchExportService;
import com.ce.pms.occupation.service.IDispatchImportService;
import com.ce.pms.occupation.service.IPerfectItemDispatchService;
import com.ce.pms.occupation.service.IPerfectItemRequisitionService;
import com.ce.pms.occupation.vo.CompletePerfectItemVO;
import com.ce.pms.occupation.vo.PerItemDispSearchVO;
import com.ce.pms.occupation.vo.PerfectItemDispatchVO;
import com.ce.pms.occupation.vo.PerfectItemRequisitionVO;
import com.ce.pms.occupation.vo.PerfectItemSearchVO;
import com.ce.pms.system.occupation.service.IContractorInfoConfigService;
import com.ce.pms.system.occupation.service.IPerfectItemTypeConfigService;
import com.ce.pms.system.occupation.vo.ContractorInfoConfigVO;
import com.ce.pms.system.occupation.vo.PerfectItemTypeConfigVO;
import com.ce.util.BlankUtil;
import com.sitechasia.webx.components.xtable.util.ExtremeUtils;
import com.sitechasia.webx.core.annotation.Out;
import com.sitechasia.webx.core.annotation.Read;
import com.sitechasia.webx.core.annotation.Scope;
import com.sitechasia.webx.core.support.Page;

/**
 * 整改派工
 *
 * @author <a href="mailto:i0o@live.cn">黄腾飞</a>
 * @Created 2009-1-7
 */

public class PerfectItemDispatchAction extends PmsBaseAction {
	private final String cache_errorList = "EXCEPTION_ERROR"; //导入时,错误数据缓存KEY
	private final String cache_warnList = "EXCEPTION_WARN";  //导入时,有疑问数据缓存KEY
	private final String cache_excelFile = "EXCEL_FILE";     //保存读入的excel文件
	private final String cache_keyword = "perfectItemDispatchId";

	public static final String				PERFECT_ITEM_REQUSITE_CACHE	= "perfectItemCache";

	private IBuildingService				buildingService;

	/**
	 * 承包商信息Service
	 */
	private IContractorInfoConfigService	contractorInfoConfigService;

	/**
	 * 详细信息
	 */
	private final String					DETAIL_PAGE					= "perfectItemRequisitionDetail";

	/**
	 * 修改页面
	 */
	private final String					EDIT_PAGE					= "perfectItemDispatchEdit";

	/**
	 * 初始化页面
	 */
	private final String					INIT_PAGE					= "perfectItemDispatchMain";

	/**
	 * 派工项目列表页面
	 */
	private final String					ITEMOFDISPALIST_PAGE		= "perfectItemOfDispaList";

	/**
	 * 列表页面
	 */
	private final String					LIST_PAGE					= "perfectItemDispatchList";

	/**
	 * 入伙整改项目Service
	 */
	private IPerfectItemDispatchService		perfectItemDispatchService;

	/**
	 * 入伙整改派工Service
	 */
	private IPerfectItemRequisitionService	perfectItemRequisitionService;

	/**
	 * 入伙整改项目类型Service
	 */
	private IPerfectItemTypeConfigService	perfectItemTypeConfigService;
	/**
	 * 文件上传组建
	 */
	private ServletFileUpload fileUpload = null;
	/**
	 * 派工项目列表
	 */
	private final String					PERITEMLISTOFCOMPELET		= "perItemListOfCompelet";

	/**
	 * 派工项目完工主页面
	 */
	private final String					REGISTERCOMPPERITEM			= "registerCompPerItem";
	/**
	 * 派工导出Service
	 */
	private IDispatchExportService dispatchExportService;
	/**
	 * 派工导入Service
	 */
	private IDispatchImportService dispatchImportService;

	/**
	 * 功能描述: 新增整改项目<br>
	 *
	 * @param perfectItemRequisitionVO Create author:胡煦 <br>
	 *            Create on:2009-1-6 <br>
	 *            Edit author: <br>
	 *            Edit on: <br>
	 *            Why: <br>
	 */
	public void addPerfectItemRequistion(
			@Read PerfectItemRequisitionVO perfectItemRequisitionVO) {
		if (this.checkPerItemReqIsExist(perfectItemRequisitionVO)) {
			this
					.addPerfectItemRequistionToCache(perfectItemRequisitionVO,
							true);
		}
	}

	/**
	 * 功能描述: 新增整改项目到缓存<br>
	 *
	 * @param perfectItemRequisitionVO Create author:胡煦 <br>
	 *            Create on:2009-1-12 <br>
	 *            Edit author: <br>
	 *            Edit on: <br>
	 *            Why: <br>
	 */
	private boolean addPerfectItemRequistionToCache(
			PerfectItemRequisitionVO perfectItemRequisitionVO, boolean isFirst) {
		boolean result = false;
		if (BlankUtil.isBlank(perfectItemRequisitionVO)) {
			return false;
		}
		LinkedList<PerfectItemRequisitionVO> list = (LinkedList<PerfectItemRequisitionVO>) this
				.getRequest().getSession().getAttribute(
						PERFECT_ITEM_REQUSITE_CACHE);
		if (list == null) {
			list = new LinkedList<PerfectItemRequisitionVO>();
		} else if (list.contains(perfectItemRequisitionVO)) {
			result = this
					.JudgeDeletePerfectItemRequisitionFromCache(perfectItemRequisitionVO) == null ? false
					: true;
			return result;
		}
		perfectItemRequisitionVO.setHasSave(ICacheManage.UNSAVE);// 未保存过
		perfectItemRequisitionVO.setOpratorStatus(ICacheManage.ADD);// 操作状态
		perfectItemRequisitionVO.setIndex(this.generationCacheIndex(list));// 设置索引
		if (isFirst) {
			list.addFirst(perfectItemRequisitionVO);
		} else {
			list.addLast(perfectItemRequisitionVO);
		}
		Collections.sort(list);
		this.getRequest().getSession().setAttribute(
				PERFECT_ITEM_REQUSITE_CACHE, list);
		result = true;
		return result;
	}

	/**
	 * 功能描述: 判断缓存中是否存在该整改项目<br>
	 *
	 * @param perfectItemRequisitionVO Create author:胡煦 <br>
	 *            Create on:2009-1-6 <br>
	 *            Edit author: <br>
	 *            Edit on: <br>
	 *            Why: <br>
	 */
	public boolean checkPerItemReqIsExist(
			@Read PerfectItemRequisitionVO perfectItemRequisitionVO) {
		List<PerfectItemRequisitionVO> list = (List<PerfectItemRequisitionVO>) this
				.getRequest().getSession().getAttribute(
						PERFECT_ITEM_REQUSITE_CACHE);
		if (!BlankUtil.isBlank(list)) {
			if (list.size() > 0) {
				for (PerfectItemRequisitionVO requisitionVO : list) {
					if (requisitionVO.getKeyword().compareTo(
							perfectItemRequisitionVO.getKeyword()) == 0
							&& ICacheManage.ADD.equals(requisitionVO
									.getOpratorStatus())) {
						return false;
					}
				}
			}
		}
		return true;
	}

	// /**
	// * 方法描述: 整改项目List页面
	// * @author 胡煦
	// * Create on:2009-1-9
	// * @param keyword 主键
	// * @return String
	// * Edit author:
	// * Edit on:
	// * 修改原因：
	// */
	// public String perItemOfDisListPage(@Read(key = "keyword") Long keyword) {
	// if (keyword != null) {
	// PerfectItemDispatchVO perfectItemDispatchVO =
	// this.perfectItemDispatchService
	// .queryperfectItemDispatchVOById(keyword);
	// this.setAttribute("perfectItemDispatchVO",
	// perfectItemDispatchVO);
	// List<PerfectItemRequisitionVO> perItemRequisitionList = new
	// ArrayList<PerfectItemRequisitionVO>();
	// Set<PerfectItemRequisitionVO> set =
	// perfectItemDispatchVO.getPerfectItemRequisitions();
	// perItemRequisitionList.addAll(set);
	// this.setAttribute("perfectItemOfDispaList",
	// perItemRequisitionList);
	// }
	// // 承包商信息List
	// List<ContractorInfoConfigVO> contractorInfoConfigList =
	// this.contractorInfoConfigService
	// .queryAllContractorInfoConfig();
	// this.setAttribute("contractorInfoConfigList", contractorInfoConfigList);
	//
	// return this.EDIT_PAGE;
	// }
	//
	/**
	 * 功能描述: 将整改项目的List集合转为Set集合<br>
	 *
	 * @param list
	 * @return Create author:胡煦 <br>
	 *         Create on:2009-1-8 <br>
	 *         Edit author: <br>
	 *         Edit on: <br>
	 *         Why: <br>
	 */
	private Set<PerfectItemRequisitionVO> convertPerfectItemList2Set(
			LinkedList<PerfectItemRequisitionVO> list) {
		if (list == null) {
			return null;
		}
		Set<PerfectItemRequisitionVO> set = new HashSet<PerfectItemRequisitionVO>();
		for (PerfectItemRequisitionVO vo : list) {
			set.add(vo);
		}
		return set;
	}

	/**
	 * 方法描述: 删除方法
	 *
	 * @author 胡煦 Create on:2009-1-9
	 * @param keyword
	 * @return void Edit author: Edit on: 修改原因：
	 */
	public void deletePerfectItemDispatch(@Read(key = "keyword") Long keyword) {
		try {
			this.perfectItemDispatchService.deletePerfectItemDispatch(keyword);
			this.renderText("true");
		} catch (RuntimeException e) {
			throw new BusinessException(
					"occupation:system_delete_inused_exception",
					BusinessException.WARNING);
		}
	}

	/**
	 * 功能描述: 删除缓存中指定的整改项目<br>
	 *
	 * @param perfectItemRequisitionVO
	 * @return Create author:胡煦 <br>
	 *         Create on:2009-1-6 <br>
	 *         Edit author: <br>
	 *         Edit on: <br>
	 *         Why: <br>
	 */
	public boolean deletePerfectItemRequistionFromCache(
			PerfectItemRequisitionVO perfectItemRequisitionVO) {
		LinkedList<PerfectItemRequisitionVO> list = this
				.getPerfectItemRequisitionListCacheByFlag(false);
		boolean flag = false;
		if (!list.contains(perfectItemRequisitionVO)) {
			return flag;
		}
		for (PerfectItemRequisitionVO requisitionVO : list) {
			if (requisitionVO.getIndex().equals(
					perfectItemRequisitionVO.getIndex())) {
				if (ICacheManage.UNSAVE.equals(requisitionVO.getHasSave())) {
					list.remove(requisitionVO);
					this.getRequest().getSession().setAttribute(
							PERFECT_ITEM_REQUSITE_CACHE, list);
				} else {
					requisitionVO.setOpratorStatus(ICacheManage.DELETE);// 操作状态
				}
				flag = true;
				break;
			}
		}
		return flag;
	}

	/**
	 * 功能描述: 删除整改项目 <br>
	 *
	 * @param index Create author:胡煦 <br>
	 *            Create on:2009-1-7 <br>
	 *            Edit author: <br>
	 *            Edit on: <br>
	 *            Why: <br>
	 */
	public void deltePerfectItemRequistion(@Read(key = "index") Integer index) {

		PerfectItemRequisitionVO itemRequisitionVO = this
				.getPerfectItemRequisitionByIndexFromCache(index);
		perfectItemDispatchService.checkDeletePerfectItemIsTrue(itemRequisitionVO.getKeyword());
		boolean result = this
				.deletePerfectItemRequistionFromCache(itemRequisitionVO);
		if (result) {
			this.renderText("true");
		} else {
			this.renderText("false");
		}
	}

	/**
	 * 方法描述: 详细页面
	 *
	 * @author 胡煦 Create on:2009-1-9
	 * @param keyword 主键
	 * @return String Edit author: Edit on: 修改原因：
	 */
	public String detailPage(@Read(key = "keyword") Long keyword) {
		PerfectItemDispatchVO perfectItemDispatchVO = this.perfectItemDispatchService
				.queryperfectItemDispatchVOById(keyword);
		this.setAttribute("perfectItemDispatchVO", perfectItemDispatchVO);
		return this.DETAIL_PAGE;
	}

	/**
	 * 方法描述: 添加或编辑主页面
	 *
	 * @author 胡煦 Create on:2009-1-9
	 * @param keyword 主键
	 * @return String Edit author: Edit on: 修改原因：
	 */
	public String editPage(
			@Read(key = "keyword") @Out(key = "keyword") Long keyword) {
		this.getRequest().getSession().setAttribute(
				PERFECT_ITEM_REQUSITE_CACHE, null);
		if (keyword != null) {
			PerfectItemDispatchVO perfectItemDispatchVO = this.perfectItemDispatchService
					.queryperfectItemDispatchVOById(keyword);
			this.setAttribute("perfectItemDispatchVO", perfectItemDispatchVO);
			new ArrayList<PerfectItemRequisitionVO>();
			Set<PerfectItemRequisitionVO> set = perfectItemDispatchVO
					.getPerfectItemRequisitions();
			if (!BlankUtil.isBlank(set)) {
				if (set.size() > 0) {
					// 将查询出来的整改项目添加到缓存
					for (PerfectItemRequisitionVO itemRequisitionVO : set) {
						this.addPerfectItemRequistionToCache(itemRequisitionVO,
								false);
					}
				}
			}

		}else{
			String dispatchNumber = perfectItemDispatchService.generateOccupationCoding();
			PerfectItemDispatchVO perfectItemDispatchVO =new PerfectItemDispatchVO();
			perfectItemDispatchVO.setDispatchNumber(dispatchNumber);
			this.setAttribute("perfectItemDispatchVO", perfectItemDispatchVO);
		}
		// 承包商信息List
		List<ContractorInfoConfigVO> contractorInfoConfigList = this.contractorInfoConfigService
				.queryAllContractorInfoConfig();
		this.setAttribute("contractorInfoConfigList", contractorInfoConfigList);

		return this.EDIT_PAGE;
	}
	/**
	 * 功能描述:初始化详细页面<br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2009-1-15  <br>
	 */
	public String initDetail(@Read(key="keyword")@Out(key="keyword")Long keyword){
		PerfectItemDispatchVO vo = perfectItemDispatchService.queryperfectItemDispatchVOById(keyword);
		setAttribute("perfectItemDispatchVO", vo);
		return "detail";
	}
	/**
	 * 功能描述:初始化详细页面的列表页面<br>
	 * 列表页面不用分页,直接查询出来就OK
	 * @param keyword
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2009-1-15  <br>
	 */
	public String initDetailList(@Read(key="keyword")Long keyword){
		PerfectItemDispatchVO vo = perfectItemDispatchService.queryperfectItemDispatchVOById(keyword);
		Set<PerfectItemRequisitionVO> set = vo.getPerfectItemRequisitions();
		setAttribute("requistionVO", set);
		setAttribute("totalRows",set == null ? Integer.valueOf(0) : set.size());
		return "detailList";
	}
	/**
	 * 功能描述: 初始化导入页面<br>
	 * @param keyword
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2009-1-15  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	public String initImport(@Read(key="keyword") @Out(key="keyword")Long keyword){
		return "import";
	}
	/**
	 * 功能描述:  导入前  需要检查下是否有错误数据、有疑问数据<br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2008-9-9  <br>
	 */
	@SuppressWarnings("unchecked")
	public String checkImportExcelFile() throws Exception{
		List<FileItem> fileItems = getFileItem();

		FileItem fileItem = null;//上传的文件
		Long perfectItemDispatchId = null; //上传的主键
		for(FileItem item : fileItems){
			if(!item.isFormField())
				fileItem = item;
			else if(item.isFormField() && "keyword".equals(item.getFieldName()))
				perfectItemDispatchId = Long.valueOf(item.getString());
		}
		//检查文件是否异常
		if(!validateFileType(fileItem.getName())){
			setAttribute("filetypeException", getLocaleMessage("charge:charege_meterdata_filetype_exception"));
			return "exceptionInfo";
		}
        //获取上传的excel
		HSSFWorkbook workbook = new HSSFWorkbook(fileItem.getInputStream());

		setAttribute(this.cache_keyword, perfectItemDispatchId,Scope.SESSION);

		Map<String,List> map = dispatchImportService.checkTheExcel(perfectItemDispatchId,workbook);
		if(map != null || map.size() > 0){
			if(map.get("error")!= null && map.get("error").size() > 0)
				setAttribute(this.cache_errorList, map.get("error"),Scope.SESSION);
			else
				removeAttribute(this.cache_errorList, Scope.SESSION);

			if(map.get("warn")!= null && map.get("warn").size() > 0)
				setAttribute(this.cache_warnList, map.get("warn"), Scope.SESSION);
			else
				removeAttribute(this.cache_warnList, Scope.SESSION);
		}
		String returnPage = "exceptionInfo";
		//如果没有错误的数据,缓存读入的文件  在导入完成后 要求remove
		if(getAttribute(this.cache_errorList, Scope.SESSION) == null){
			setAttribute(this.cache_excelFile, workbook,Scope.SESSION);
			returnPage = "exceptionInfo";
		}
		if(getAttribute(this.cache_errorList, Scope.SESSION) == null &&getAttribute(this.cache_warnList, Scope.SESSION) == null){
			returnPage = "importFile";
		}
		return returnPage;
	}
	/**
	 * 功能描述:导入文件<br>
	 * Create author:yixianjian <br>
	 * Create on:2009-1-15  <br>
	 */
	public String importFile(){
        try {
			//获取上传的excel
			HSSFWorkbook workbook = (HSSFWorkbook)getAttribute(this.cache_excelFile, Scope.SESSION);
			Long keyword = (Long)getAttribute(this.cache_keyword,Scope.SESSION);
			dispatchExportService.checkDispatchIsComp(keyword);
			dispatchImportService.readExcelAndSave(workbook,keyword,super.getUserId());
			//清空缓存
			removeAttribute(this.cache_errorList, Scope.SESSION);
			removeAttribute(this.cache_warnList, Scope.SESSION);
			removeAttribute(this.cache_excelFile, Scope.SESSION);
			removeAttribute(this.cache_keyword,Scope.SESSION);
			//设置成功标识
			setAttribute("success", Boolean.valueOf(true));
			return "exceptionInfo";
		} catch (BusinessException e) {
			throw e;
		}
	}
	/**
	 * 功能描述: 导出文件 <br>
	 * Create author:yixianjian <br>
	 * Create on:2008-8-28  <br>
	 * @throws Exception
	 */
	public void exportFile(@Read(key="keyword")Long keyword) throws Exception{
		try {
			dispatchExportService.checkDispatchIsComp(keyword);
			HSSFWorkbook hssfWorkdbook = dispatchExportService.createHSSFWorkbook(keyword);
			String fileName = getFileName(keyword);
			getResponse().setHeader("Content-Disposition", "attachment;" + fileName);
			getResponse().setContentType("application/vnd.ms-excel");
			hssfWorkdbook.write(getResponse().getOutputStream());
			getResponse().getOutputStream().flush();
			getResponse().getOutputStream().close();
		} catch (BusinessException e) {
			throw e;
		}
	}


	/**
	 * 功能描述:初始化异常主页面<br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2009-1-15  <br>
	 */
	public String listExceptionMain(){
		return "exceptionMain";
	}
	/**
	 * 功能描述: 在导入时发生错误,需要列出发生错误的列表,这个方法就是初始化错误列表<br>
	 * @param type
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2009-1-15  <br>
	 */
	public String listException(@Read(key="type") @Out(key="type") String type){
		String cacheKey = "error".equals(type) ? this.cache_errorList : ("warn".equals(type) ? this.cache_warnList : null);
		if(cacheKey == null)
			throw new UILayerException("charge:charge_meterData_error_type_exception",UILayerException.ERROR);
		List list = (List)getAttribute(cacheKey, Scope.SESSION);
		Integer totalRows = list != null ? list.size() : Integer.valueOf(0);
		setAttribute("totalRows", Integer.valueOf(totalRows));
		return "exceptionList";
	}
	/**
	 * 功能描述:获取导出的文件名<br>
	 * @param keyword
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2009-1-15  <br>
	 */
	private String getFileName(Long keyword) {
		PerfectItemDispatchVO vo = perfectItemDispatchService.queryperfectItemDispatchVOById(keyword);
		StringBuffer fileName = new StringBuffer("filename=");
		fileName.append(vo.getDispatchNumber());
		fileName.append(".xls");
		return fileName.toString();
	}
	/**
	 * 功能描述:获取上传到表单域<br>
	 * @return
	 * Create author:yixianjian <br>
	 * Create on:2009-1-15  <br>
	 */
	private List<FileItem> getFileItem(){
		//这段代码实在只应该实例化一次的
		if(fileUpload == null){
	        DiskFileItemFactory factory=new DiskFileItemFactory();
	        factory.setSizeThreshold(4096);
	        fileUpload=new ServletFileUpload(factory);
		}
        try{
            //开始读取上传信息
            List<FileItem> filedList  = fileUpload.parseRequest(getRequest());
            return filedList;
        }catch(Exception e){
        	throw new UILayerException(getLocaleMessage("charge:charege_meterdata_read_file_exception"));
        }
	}
	/**
	 * 功能描述:  验证文件格式必须为xsl，office其他版本(如office 2007 为xslx)不支持,其他文件类型不支持<br>
	 * @param file
	 * Create author:yixianjian <br>
	 * Create on:2008-8-27  <br>
	 */
	private boolean validateFileType(String fileName){
		String fileNameTemp = fileName.toLowerCase();
		if(fileNameTemp.endsWith("xls")) return true;
		return false;
	}
	/**
	 * 方法描述: 派工新增或修改方法
	 *
	 * @author 胡煦 Create on:2009-1-9
	 * @param perfectItemRequisitionVO
	 * @return void Edit author: Edit on: 修改原因：
	 */
	public void editPerfectItemDispatch(
			@Read PerfectItemDispatchVO perfectItemDispatchVO) {
		// 获取整改项目List
		Set<PerfectItemRequisitionVO> perfectItemOfDispaSet = this
				.convertPerfectItemList2Set(this
						.getPerfectItemRequisitionListCacheByFlag(true));
		if (!BlankUtil.isBlank(perfectItemOfDispaSet)) {
			perfectItemDispatchVO.getPerfectItemRequisitions().clear();
			perfectItemDispatchVO.getPerfectItemRequisitions().addAll(
					perfectItemOfDispaSet);
		}
		this.setAttribute("perfectItemDispatchVO", perfectItemDispatchVO);

		if (BlankUtil.isBlank(perfectItemDispatchVO.getKeyword())) {

			this.perfectItemDispatchService
					.addPerfectItemDispatch(perfectItemDispatchVO);
		} else {
			this.perfectItemDispatchService
					.editPerfectItemDispatch(perfectItemDispatchVO);
		}
		this.getRequest().getSession().setAttribute(
				PERFECT_ITEM_REQUSITE_CACHE, null);
		this.renderText("true");

	}

	private Integer generationCacheIndex(
			LinkedList<PerfectItemRequisitionVO> list) {
		if (list == null) {
			return -1;
		} else if (0 == list.size()) {
			return 1;
		}
		Integer max = 1;
		for (ICacheManage manage : list) {
			if (max < manage.getIndex()) {
				max = manage.getIndex();
			}
		}
		return max + 1;
	}

	/**
	 * 功能描述: 得到缓存中已删除的整改项目列表 <br>
	 *
	 * @return Create author:胡煦 <br>
	 *         Create on:2009-1-6 <br>
	 *         Edit author: <br>
	 *         Edit on: <br>
	 *         Why: <br>
	 */
	private LinkedList<PerfectItemRequisitionVO> getDeletePerfectItemRequisitionListCache() {
		// 得到全部的
		LinkedList<PerfectItemRequisitionVO> allList = this
				.getPerfectItemRequisitionListCacheByFlag(false);
		ListIterator<PerfectItemRequisitionVO> listIter = allList
				.listIterator();
		while (listIter.hasNext()) {
			PerfectItemRequisitionVO requisitionVO = listIter.next();
			// 把缓存中状态为未删除的过滤掉
			if (!ICacheManage.DELETE.equals(requisitionVO.getOpratorStatus())) {
				listIter.remove();
			}
		}
		return allList;
	}

	/**
	 * 功能描述: 根据下标index从缓存中获取指定整改项目 <br>
	 *
	 * @param index
	 * @return Create author:胡煦 <br>
	 *         Create on:2009-1-7 <br>
	 *         Edit author: <br>
	 *         Edit on: <br>
	 *         Why: <br>
	 */
	private PerfectItemRequisitionVO getPerfectItemRequisitionByIndexFromCache(
			Integer index) {
		if (BlankUtil.isBlank(index)) {
			return null;
		}
		LinkedList<PerfectItemRequisitionVO> list = this
				.getPerfectItemRequisitionListCacheByFlag(false);
		if (list == null) {
			return null;
		}
		for (PerfectItemRequisitionVO vo : list) {
			if (index.equals(vo.getIndex())) {
				return vo;
			}
		}
		return null;
	}

	/**
	 * 功能描述: 得到缓存中整改项目列表，如果没有数据，
	 * 此方法返回一个实例化的空列表容器,如果operatorFlag参数为<b><i>true</i></b>值，
	 * 则会返回一个过滤了删除状态记录的列表，否则完整返回<br>
	 *
	 * @param operatorFlag
	 * @return Create author:胡煦 <br>
	 *         Create on:2009-1-6 <br>
	 *         Edit author: <br>
	 *         Edit on: <br>
	 *         Why: <br>
	 */
	private LinkedList<PerfectItemRequisitionVO> getPerfectItemRequisitionListCacheByFlag(
			boolean operatorFlag) {
		LinkedList<PerfectItemRequisitionVO> list = (LinkedList<PerfectItemRequisitionVO>) this
				.getRequest().getSession().getAttribute(
						PERFECT_ITEM_REQUSITE_CACHE);
		if (!operatorFlag) {
			return list == null ? new LinkedList<PerfectItemRequisitionVO>()
					: list;
		}
		LinkedList<PerfectItemRequisitionVO> noDelList = new LinkedList<PerfectItemRequisitionVO>();
		// 把缓存中操作状态为已删除的过滤掉
		if (list != null) {
			for (PerfectItemRequisitionVO requisitionVO : list) {
				if (ICacheManage.DELETE
						.equals(requisitionVO.getOpratorStatus())) {
					continue;
				}
				noDelList.add(requisitionVO);
			}
		}
		return noDelList;
	}

	/**
	 * 功能描述: 计算缓存中的记录总数 <br>
	 *
	 * @return Create author:胡煦 <br>
	 *         Create on:2009-1-7 <br>
	 *         Edit author: <br>
	 *         Edit on: <br>
	 *         Why: <br>
	 */
	private Integer getTotalRowsFromCache() {
		LinkedList<PerfectItemRequisitionVO> list = (LinkedList<PerfectItemRequisitionVO>) this
				.getRequest().getSession().getAttribute(
						PERFECT_ITEM_REQUSITE_CACHE);
		int totalRows = 0;
		if (list != null) {
			totalRows = list.size();
			for (PerfectItemRequisitionVO manage : list) {
				if (ICacheManage.DELETE.equals(manage.getOpratorStatus())) {
					totalRows--;
				}
			}
		}
		return totalRows;
	}

	/**
	 * 初始化页面
	 *
	 * @return
	 * @author <a href="mailto:i0o@live.cn">黄腾飞</a>
	 * @created 2009-1-7
	 */
	public String initPage() {
		// 承包商信息List
		List<ContractorInfoConfigVO> contractorInfoConfigList = this.contractorInfoConfigService
				.queryAllContractorInfoConfig();
		this.setAttribute("contractorInfoConfigList", contractorInfoConfigList);

		return this.INIT_PAGE;
	}

	/**
	 * 功能描述: 功能描述: 整改项目列表 <br>
	 *
	 * @param
	 * @return Create author:胡煦 <br>
	 *         Create on:2009-1-12 <br>
	 *         Edit author: <br>
	 *         Edit on: <br>
	 *         Why: <br>
	 */
	public String initPerfectItemList() {
		List<PerfectItemRequisitionVO> list = null;
		this.setAttribute("perfectItemOfDispaList", list);
		this.setAttribute("totalRows", new Integer(5));
		return this.ITEMOFDISPALIST_PAGE;
	}

	/**
	 * 功能描述: 整改项目列表(缓存) <br>
	 *
	 * @param
	 * @return Create author:胡煦 <br>
	 *         Create on:2009-1-6 <br>
	 *         Edit author: <br>
	 *         Edit on: <br>
	 *         Why: <br>
	 */
	public String initPerfectItemListCache() {
		List<PerfectItemRequisitionVO> list = this
				.getPerfectItemRequisitionListCacheByFlag(true);
		this.setAttribute("perfectItemOfDispaList", list);
		this.setAttribute("totalRows", this.getTotalRowsFromCache());
		return this.ITEMOFDISPALIST_PAGE;
	}

	/**
	 * 功能描述:初始化派工列表主页面<br>
	 *
	 * @param <br>
	 * @return<br> Create author:xuhaidui<br>
	 *             Create on:2009-1-14<br>
	 *             Edit author:<br>
	 *             Edit on:<br>
	 *             Why:<br>
	 */

	public String initPerItemReqsAdd() {

		List<PerfectItemTypeConfigVO> list = this.perfectItemTypeConfigService
				.queryAllPerfectItemTypeConfig();
		List<BuildingVO> buildingList = this.buildingService
				.getAllBuildingList();

		this.setAttribute("buildingList", buildingList);
		this.getRequest().setAttribute("ItemType", list);

		return "perfectItemReqOfDispAdd";
	}

	/**
	 * 方法描述: 派工完工登记項目列表查询方法
	 *
	 * @author 胡煦 Create on:2009-1-13
	 * @param keyword
	 * @return String Edit author: Edit on: 修改原因：
	 */
	public String initRegisterCompPerItem(@Read(key = "keyword") Long keyword) {
		List<PerfectItemRequisitionVO> list = this.perfectItemRequisitionService
				.queryNoComPerItemSByDispatchId(keyword);

		if (list != null) {
			this.setAttribute("perItemReqsOfCompelet", list);
			this.setAttribute("totalRows", new Integer(list.size()));
		} else {
			this.setAttribute("totalRows", new Integer(0));
		}
		return this.PERITEMLISTOFCOMPELET;
	}

	/**
	 * 功能描述: 判断一个整改项目是不是存在于缓存中的已被置为删除状态的数据，如果存在就恢复过来 <br>
	 *
	 * @param perfectItemRequisitionVO
	 * @return Create author:胡煦 <br>
	 *         Create on:2009-1-6 <br>
	 *         Edit author: <br>
	 *         Edit on: <br>
	 *         Why: <br>
	 */
	private PerfectItemRequisitionVO JudgeDeletePerfectItemRequisitionFromCache(
			PerfectItemRequisitionVO perfectItemRequisitionVO) {
		List<PerfectItemRequisitionVO> list = this
				.getDeletePerfectItemRequisitionListCache();
		for (PerfectItemRequisitionVO tempchvo : list) {
			// 如果存在于缓存中，是删除状态的，则恢复过来，并设置持久属性为SAVED，状态属性为EDIT
			if (perfectItemRequisitionVO.equals(tempchvo)) {
				tempchvo.setHasSave(ICacheManage.SAVED);
				tempchvo.setOpratorStatus(ICacheManage.EDIT);
				return tempchvo;
			}
		}
		return null;
	}

	/**
	 * 列表
	 *
	 * @return
	 * @author <a href="mailto:i0o@live.cn">黄腾飞</a>
	 * @created 2009-1-7
	 */
	public String listPage() {
		this.setAttribute("totalRows", new Integer(0));
		return this.LIST_PAGE;
	}

	/**
	 * 功能描述:派工列表页面<br>
	 *
	 * @param <br>
	 * @return<br> Create author:xuhaidui<br>
	 *             Create on:2009-1-14<br>
	 *             Edit author:<br>
	 *             Edit on:<br>
	 *             Why:<br>
	 */
	public String perfectItemReqOfDispList(
			@Read(key = "buildingId") Long buildingId,
			@Read(key = "perfectItemTypeConfigId") Long perfectItemTypeConfigId) {

		List<PerfectItemRequisitionVO> list = new ArrayList();

		PerfectItemSearchVO searchVO = new PerfectItemSearchVO();
		searchVO.setBuildingId(buildingId);
		searchVO.setDispatchYn("0");
		searchVO.setCompleteYn("0");
		searchVO.setPerfectItemTypeConfigId(perfectItemTypeConfigId);
		searchVO.setSortStr(ExtremeUtils.getOrderString(this.getRequest()));
		list = this.perfectItemRequisitionService
				.queryPerItemListByDispatchId(searchVO);
		this.setAttribute("selectList", list);
		this.setAttribute("totalRows", new Integer(list == null ? 0 : list
				.size()));
		return "perfectItemReqOfDispList";
	}

	/**
	 * 方法描述: 派工单列表查询
	 *
	 * @author 胡煦 Create on:2009-1-9
	 * @param
	 * @return String Edit author: Edit on: 修改原因：
	 */
	public String queryPerItemDispaListPage(
			@Read(key = "ec_p", defaultValue = "1") Integer pageNO,
			@Read(key = "ec_crd", defaultValue = "15") Integer pageSize,
			@Read(key = "contractorInfoId")@Out(key="contractorInfoId") Long contractorInfoId,
			@Read(key = "houseId")@Out(key="houseId") Long houseId,
			@Read(key = "overflowHight",defaultValue="")@Out(key="overflowHight") String overflowHight) {

		// 获取整改项目Page
		PerItemDispSearchVO perItemDispSearchVO = new PerItemDispSearchVO();
		perItemDispSearchVO.setPageNo(pageNO);
		perItemDispSearchVO.setPageSize(pageSize);
		perItemDispSearchVO.setSortStr(ExtremeUtils.getOrderString(this.getRequest()));
		perItemDispSearchVO.setContractorInfoId(contractorInfoId);
		perItemDispSearchVO.setHouseId(houseId);
		Page perItemDispatchPage = this.perfectItemDispatchService
				.queryPerfectItemDispatchVOByPage(perItemDispSearchVO);
		this.setAttribute("perfectItemDispatchList", perItemDispatchPage
				.getResult());
		this.setAttribute("totalRows", Long.valueOf(
				perItemDispatchPage.getTotalCount()).intValue());
		return this.LIST_PAGE;
	}

	/**
	 * 方法描述:完工登记
	 *
	 * @author 胡煦 Create on:2009-1-14
	 * @param keyword
	 * @return String Edit author:黄腾飞
	 *  Edit on: 修改原因：
	 */
	public void registerCompPerItem(
			@Read CompletePerfectItemVO completePerfectItemVO,@Read(key="perItemReqIdSet") String perItemReqIdSet) {
		try {

			if(!BlankUtil.isBlank(perItemReqIdSet)){
				Set<Long> perItemReqId = new HashSet<Long>();
				String[] perItemReqIdTmp =  perItemReqIdSet.split(",");

				for(String tmp :perItemReqIdTmp){
					perItemReqId.add(Long.valueOf( tmp ));
				}

				completePerfectItemVO.setPerItemReqIdSet(perItemReqId);
			}




			this.perfectItemDispatchService
					.registerCompPerItem(completePerfectItemVO);
			this.renderText("true");
		} catch (RuntimeException re) {
			throw re;
		}
	}

	/**
	 * 方法描述:完工登记页面
	 *
	 * @author 胡煦 Create on:2009-1-14
	 * @param keyword
	 * @return String Edit author: Edit on: 修改原因：
	 */
	public String registerCompPerItemPage(
			@Read(key = "keyword") @Out(key = "perItemDispatchId") Long keyword) {
		return this.REGISTERCOMPPERITEM;
	}

	/**
	 * 功能描述:保存派工列表<br>
	 *
	 * @param <br>
	 * @return<br> Create author:xuhaidui<br>
	 *             Create on:2009-1-14<br>
	 *             Edit author:<br>
	 *             Edit on:<br>
	 *             Why:<br>
	 */
	public void savePerfectItemReqOfDispList(
			@Read(key = "selectIdStr") String selectIdStr) {
		if (!BlankUtil.isBlank(selectIdStr)) {
			String[] array = selectIdStr.split(",");
			for (String id : array) {
				PerfectItemRequisitionVO vo = this.perfectItemRequisitionService
						.queryPerfectItemRequisitionVOById(Long.valueOf(id));
				if (!BlankUtil.isBlank(vo)) {
					this.addPerfectItemRequistion(vo);
				}
			}

		}

	}

	public void setBuildingService(IBuildingService buildingService) {
		this.buildingService = buildingService;
	}

	public void setContractorInfoConfigService(
			IContractorInfoConfigService contractorInfoConfigService) {
		this.contractorInfoConfigService = contractorInfoConfigService;
	}

	public void setDispatchExportService(
			IDispatchExportService dispatchExportService) {
		this.dispatchExportService = dispatchExportService;
	}

	public void setDispatchImportService(
			IDispatchImportService dispatchImportService) {
		this.dispatchImportService = dispatchImportService;
	}

	public void setPerfectItemDispatchService(
			IPerfectItemDispatchService perfectItemDispatchService) {
		this.perfectItemDispatchService = perfectItemDispatchService;
	}

	public void setPerfectItemRequisitionService(
			IPerfectItemRequisitionService perfectItemRequisitionService) {
		this.perfectItemRequisitionService = perfectItemRequisitionService;
	}

	public void setPerfectItemTypeConfigService(
			IPerfectItemTypeConfigService perfectItemTypeConfigService) {
		this.perfectItemTypeConfigService = perfectItemTypeConfigService;
	}

}
